import axios from 'axios';
import {
	Message,Loading 
} from 'element-ui';
import store from '@/store'
import router from '@/router/index.js'

import { MyLoading } from "@/components/loading";



//给axios添加拦截器 请求拦截器、响应拦截
//给axios请求前设置下信息
let loadId = null;
// Add a request interceptor
axios.interceptors.request.use(function(config) {
	// Do something before request is sent
	//console.log("config",config)
	//从store对象中获取  token
	//console.log("store.getters.getToken",store.getters.getToken)
	if (store.getters.getToken) {
		config.headers["token"] = store.getters.getToken
	}
	
	//请求网络 打开loading
	// loadId = Loading.service(
	// 	{ fullscreen: true }
	// );
	
	MyLoading.service()
	return config;
});


axios.interceptors.response.use(
  response => {
	//关闭loading
	// loadId.close();
	MyLoading.close()
    return response
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  }
);






let http = {
	post(url, callback, params = {}) {
		// console.log("params:",params)
		let urlSeachParames = new URLSearchParams();
		for (let key in params) {

			// console.log("key:", key)
			urlSeachParames.append(key, params[key])
		}

		axios.post(url, urlSeachParames).
		then((ret) => {
			//axios的状态
			if (ret.status == 200) { //网络请求是通的，axios的状态
				let response = ret.data; //响应结果
				let {
					code,
					message,
					obj
				} = response;
				if (code == 200) {
					callback(obj)
				}else if(code==401){
					Message.error({
						message: "登录超时，请重新登录",
						duration: 2000,
						offset: 200
					})
					router.push({path:'/login'})
				}else if(code==404){
					Message.error({
						message: message||"请求的路径不正确",
						duration: 2000,
						offset: 200
					})
				} else {
					alert("出错了:" + msg)
				}
			}else{
				
			}

		})
	},
	get(url, callback, params = {}) {
		//'/api/channel?_type=queryById&id='+this.id
		axios.get(url, {
			params: params
		}).
		then((ret) => {
			// console.log("ret", ret);
			if (ret.status == 200) { //网络请求是通的，axios的状态
				let response = ret.data; //响应结果  CommonResult
				// console.log("response", response)
				let {
					code,
					message,
					obj
				} = response;
				if (code == 200) { //Controller返回的请求状态是200
					// console.log("obj", obj)
					callback(obj);
				} else if(code==401){
					Message.error({
						message: "登录超时，请重新登录",
						duration: 2000,
						offset: 200
					})
					router.push({path:'/login'})
				}else if(code==404){
					Message.error({
						message: message||"请求的路径不正确",
						duration: 2000,
						offset: 200
					})
				}else { //401  404 
					// alert("出错了:"+message)
					Message.error({
						message: message,
						duration: 2000,
						offset: 200
					})
				}
			}

		})
	}
}

export default http
